<template>
  <view>
    <view class="info-box">
      <view class="margin-box">
        <view class="title">商品信息</view>
        <block v-if="orderType == 1">
          <view class="info-flex">
            <view class="flex-label">出行日期</view>
            <view class="flex-content">{{ infoData.travelDate }}</view>
          </view>
          <!-- <view class="info-flex" v-if="infoData.itineraryDetails && infoData.itineraryDetails.length > 0">
            <view class="flex-label">行程明细</view>
            <view class="flex-content active">
              <view
                v-for="(item, index) in infoData.itineraryDetails"
                :key="index"
                > <text>DAY{{index + 1}}</text> {{ item }}</view
              >
            </view>
          </view> -->
          <view class="info-flex" v-if="infoData.includeProducts && infoData.includeProducts.length > 0">
            <view class="flex-label">包含商品</view>
            <view class="flex-content active">
              <view
                v-for="(item, index) in infoData.includeProducts"
                :key="index"
                class="view"
                >{{ index + 1 }}. {{ item }}</view
              >
            </view>
          </view>
          <view class="info-flex">
            <view class="flex-label">商品总价</view>
            <view class="flex-content">¥{{ infoData.price }}元 </view>
          </view>
        </block>
        <block v-if="orderType == 2">
          <view class="info-flex">
            <view class="flex-label">入住日期</view>
            <view class="flex-content"
              >{{ hotelOrderInfo.startTime }} ～
              {{ hotelOrderInfo.endTime }}，{{hotelOrderInfo.quantity}}晚
            </view>
          </view>
          <view class="info-flex">
            <view class="flex-label">房型信息</view>
            <view class="flex-content active">
              <view
              class="view"
                >{{ hotelOrderInfo.productName }} |
                {{ hotelOrderInfo.skuName }}</view
              >
            </view>
          </view>
          <view class="info-flex active">
            <view class="flex-label">房间数量</view>
            <view class="flex-right-box">
              <img
                class="change-btn"
                src="https://vtrip-sfile.oss-cn-shenzhen.aliyuncs.com/h5AndMini/2023-6-12/ai-change-1.png"
                @click="changeNight(0)"
                :data-spmCntSuffix="'.changeBtn@1.changeNight@'"
                :data-custom="1"
                :data-spm="{}"
              />
              <view class="roomNight">{{ roomNight }}</view>
              <img
                class="change-btn"
                src="https://cdn1.visiotrip.com/h5AndMini/2023-09-14/ai-change-2.png"
                @click="changeNight(1)"
                :data-spmCntSuffix="'.changeBtn@1.changeNight@'"
                :data-custom="2"
                :data-spm="{}"
              />
            </view>
          </view>
          <view class="info-flex" v-if="hotelOrderInfo.cancelRule">
            <view class="checkInTime">{{ hotelOrderInfo.cancelRule }}</view>
          </view>
        </block>
      </view>
    </view>
    <!--预定信息-->
    <view style="padding: 0 0 20rpx 0">
      <!-- <aiFormBox
        ref="carRef"
        @openEdit="openEdit"
        @cancel="cancel"
        :travelerWith="travelerWith"
        @handlerFlag="$emit('handlerFlag')"
        @changeFormData="changeFormData"
        @morePeople="morePeople"
        :travellerNum="roomNight"
        :visitorCopies="visitorCopies"
        :form-title="'游客信息'"
      >
      </aiFormBox> -->
    </view>
  </view>
</template>

<script>
// import aiFormBox from "../aiTripPeople/index.vue";
import common from "../../utils/common.js";
import formBox from "../formBox/index.vue";
export default {
  components: {
    // aiFormBox,
    formBox
  },
  props:{
    travelerWith:{
      type:Boolean
    }
  },
  data() {
    return {
      orderData: undefined,
      acquiesce: false,
      formData: [],
      visitorCopies: false,
      travelerNum: 1,
      infoData: "",
      uuid: "",
      roomNight: 1,
      hotelOrderInfo: "",
      orderType: "",
      price: 0,
      totalPrice: 0,
      productName: "",
      title: "",
      tripPeopleArr: [],
    };
  },
  methods: {
    init(data) {
      // code == 1 行程  code == 2 酒店
      this.orderData = data
      this.orderType = data.code;
      // uni.$emit(Events.chooseTraveler, []); //清空选择出行人
      this.$refs.carRef.reloadDataTraveler([]); //清空选择出行人
      this.uuid = common.setUuid();
      if (this.orderType == 1) {
        this._sendRequest(data.params);
      } else if (this.orderType == 2) {
        this.getHotelOrder(data.params);
      }
    },
    acquiesceClick() {
      this.acquiesce = !this.acquiesce;
    },
    async getContactsList() {
      let res = await this.$aiRequest({
        url: "/app/my/contacts/appContactsList",
        method: "POST",
        params: {},
      });
      if (res.success) {
        this.contactsList = [];
        const data = res.data;
        data.forEach((item) => {
          item.selected = false;
        });
        this.contactsList = data;
      }
    },
    //设置数据
    setInitData(res) {
      try{
      this.roomNight = 1
      let data = res;
      let productCustomerInfoDTOList = [];
      let contactCustomerInfoDTOList = [];
      let BookerList = [];
      let TravelerList = [];
      if (this.orderType == 1) {
        //行程
        BookerList = data.subOrderBookerResponseList;
        TravelerList = data.subOrderTravelerResponseList;
        this.price = data.price;
        this.title = data.dspName;
        // this.roomNight = data.travellerNum;
        let subOrderTravelerResponseList = data.subOrderTravelerResponseList.filter(item=>item.customerInfoId!='74')
        this.$store.commit('product/SET_CUSTOMER_INFO_LIST', subOrderTravelerResponseList);
      } else if (this.orderType == 2) {
        //酒店 需要除去 联系人模板 customerInfoId == 74的项
        BookerList =
          data.productCustomerInfoDTOList.length > 0
            ? data.productCustomerInfoDTOList.filter((item) => {
                return item.customerInfoId != 74 && item.customerInfoId != 73;
              })
            : [];
        TravelerList =
          data.contactCustomerInfoDTOList.length > 0
            ? data.contactCustomerInfoDTOList.filter((item) => {
                return item.customerInfoId != 74 && item.customerInfoId != 73;
              })
            : [];
        this.price = data.sellPrice;
        this.title = data.stdName;
        this.applyDate = data.startTime
        // 设置出行人模板，给后续的新增出行人使用 vuex
        let newContactCustomerInfoDTOList = data.contactCustomerInfoDTOList.filter(item=>item.customerInfoId!='74')
        this.$store.commit('product/SET_CUSTOMER_INFO_LIST', newContactCustomerInfoDTOList);
      }
      // 联系人信息
      if (BookerList.length > 0) {
        productCustomerInfoDTOList = common.formattingForm(
          BookerList,
          "联系人"
        );
      }
      // 出行人信息
      if (TravelerList.length > 0) {
        contactCustomerInfoDTOList = common.formattingForm(
          TravelerList,
          "出行人"
        );
      }
      // 是否根据间数需要多个出行人
      this.visitorCopies = data.visitorCopies;
      this.$nextTick(() => {
        // 在此处执行你要执行的函数
        let linkmanArr = productCustomerInfoDTOList;
        let tripPeopleArr = contactCustomerInfoDTOList;
        this.tripPeopleArr = tripPeopleArr;
        //  this.formData 先添加联系人，再添加出行人。数组来维护出行人个数以及显示  ，后续可以直接把formData 放进vuex，通过维护这个字段数据
        let formData = []
        if (linkmanArr.length > 0) {
          formData.push(linkmanArr);
        }
        if (tripPeopleArr.length > 0) {
          formData.push(tripPeopleArr);
        }
        this.$store.commit("SET_FORMDATA", formData);
        // 行程的个数是没有添加减少按钮，通过服务端接口返回个数
        if(this.orderType == 1) {
          if(data.travellerNum>1){
            for (let index = 1; index < data.travellerNum; index++) {
              this.changeNight(1,1)
            }
            
          }
        }
        // 获取模板完成获取默认预订人
        this.$refs.carRef.getReservation();
        if (this.orderType == 2) {
          this.$refs.carRef.getContactsList()
        }
        //请求完数据执行组件回调 弹出弹框
        this.$emit("moduleCallBack", {
          price: this.price,
          title: this.title,
        });
      });
      } catch (e) {
        console.log(e, '888888888888888888888888')
      }
    },
    //获取行程下单页数据
    async _sendRequest(data) {
      this.formData = [];
      const that = this;
      let itineraryId = data.itineraryId;
      let res = await this.$aiRequest({
        url: `/ai/aihub/chat/purchaseItinerary/${itineraryId}`,
        method: "GET",
      });
      if (res.success) {
        this.infoData = res.data;
        this.setInitData(res.data);
      } else {
        uni.showToast({
          title: "网络异常，请稍后重试~",
          icon: "none",
        });
      }
    },
    //获取酒店下单页数据
    async getHotelOrder(data) {
      this.formData = [];
      let params = data;
      let res = await this.$aiRequest({
        url: `/product/hotel/newHotelPlaceOrder`,
        method: "POST",
        params,
      });
      if (res.success) {
        this.hotelOrderInfo = res.data;
        if (res.data.minRoomNumberLimit) {
          this.roomNight = +res.data.minRoomNumberLimit || 1
          let x = this.$BigNumber(res.data.sellPrice).times(res.data.minRoomNumberLimit).toString(); //防止js计算精度，使用BigNumber.
          console.log(x);
          this.$emit("setParentLevelData", {
            totalPrice: x,
          });
        }
        // 酒店详情数据
        this.$emit('hotelDetails',res.data)
        // this.hotelOrderInfo.travelDate = res.data.startTime;
        this.setInitData(res.data);
      }
    },
    // 取消时重置当前模板数据，防止数据篡改
    cancel({newFormData,contactIndex, contact}){
      const findIndexArr = this.formData.map(e => {
        return e[0].contactId || ''
      })
      const idx = findIndexArr.findIndex(e => e == contact?.contactId)
      if (idx > -1) {
        this.formData[idx] = this.tripPeopleArr
      }
    },
    //监听子组件方法
    changeFormData(data) {
      let that = this;
      that.$readySubmit(data, (customerInfoCreateRequestList) => {
        that.submitPay(customerInfoCreateRequestList);
      });
    },
    //提交订单
    async submitPay(customerInfoCreateRequestList) {
      let params = "";
      if (this.orderType == 1) {
        //ai行程创建订单参数
        params = {
          applyDate: this.infoData.travelDate,
          customerInfoCreateRequestList: customerInfoCreateRequestList,
          dspId: this.infoData.dspId,
          orderQuantities: 1,
          price: this.infoData.price,
          productInfoList: this.infoData.productInfoList,
          salePrice: this.infoData.price,
          createOrderUniqueId: this.uuid,
          itineraryId: this.infoData.itineraryPlanId,
        };
      } else if (this.orderType == 2) {
        //新日历酒店创建订单参数
        params = {
          applyDate: this.hotelOrderInfo.startTime,
          customerInfoCreateRequestList: customerInfoCreateRequestList,
          dspId: `${this.hotelOrderInfo.stdId},${this.hotelOrderInfo.productId}`,
          sukId: this.hotelOrderInfo.skuId,
          orderQuantities: this.roomNight,
          price: this.hotelOrderInfo.sellPrice,
          productInfoList: this.hotelOrderInfo.productInfoList,
          salePrice: this.hotelOrderInfo.sellPrice,
          createOrderUniqueId: this.uuid,
          buyerId: uni.getStorageSync("currUser").id,
        };
      }

      if (!this.$store.$state.payState) {
        return false;
      }
      this.$store.commit("SET_PAY_STATE", false);
      await this.$store.dispatch("product/GET_ORDER", params);
      const result = this.$store.$state.product.createOrder;
      if (result) {
        let weChatApplet = {
          orderId: result,
          payer: uni.getStorageSync("openid"),
          totalAmount: this.price,
          hopRoute: 2, //支付完成后弹框
          title: this.title,
        };
        this.$wxPay(
          {...this.orderData, ...weChatApplet},
          (code) => {
            this.$store.commit("SET_PAY_STATE", true);
          },
          () => {
            this.$emit("payCall", weChatApplet);
            /// 旅行管家下的半弹窗发送事件 通知插入下单消息
            uni.$emit('payMess',{ skuId: this.hotelOrderInfo.skuId, itineraryPlanId: this.infoData.itineraryPlanId, orderId: weChatApplet.orderId })
            console.log("弹框11111111111");
          }
        );
        this.$bridge.closeWebPopup()
      } else {
        this.$store.commit("SET_PAY_STATE", true);
        this.uuid = common.setUuid();
      }
    },
    //编辑出行人
    openEdit(code) {
      this.showSubmit = code
      this.$emit('openEdit')
    },
    //提交订单
    submitOrder() {
      this.$refs.carRef.submit();
    },
    //更多出行人
    morePeople(data) {
      this.$emit("morePeople", data);
    },
   changeNight(code, w) {
      if (code === 1) {
        //加间夜
        try {
        // 控制选择数量
        if (this.hotelOrderInfo.roomNumberLimit) {
          if (this.roomNight >= this.hotelOrderInfo.roomNumberLimit) {
            uni.showToast({
              title: `最多选择${this.hotelOrderInfo.roomNumberLimit}间`,
              icon: "none",
            });
            return;
          }
        }
         this.roomNight++;
        let x = this.$BigNumber(this.price).times(this.roomNight).toString(); //防止js计算精度，使用BigNumber.
        this.$emit("setParentLevelData", {
          totalPrice: x,
        });
        if (
          this.tripPeopleArr.length > 0 &&
          (w||this.tripPeopleArr[0].visitorCopies )
        ) {
          console.log(this.tripPeopleArr[0].visitorCopies);
          let pushArr = JSON.parse(JSON.stringify(this.tripPeopleArr));
          pushArr.map((item) => {
            item.ranking = num;
          });
          // this.commit('SET_FORMDATA_PUSH')
          this.$store.commit("SET_FORMDATA_PUSH", pushArr);
          // this.formData.push(pushArr);
          this.$refs.carRef.getReservation();
        }
        } catch (error) {
          
        }

      } else {
        //减间夜
        // 控制选择数量
        if (this.hotelOrderInfo.minRoomNumberLimit) {
          if (this.roomNight <= this.hotelOrderInfo.minRoomNumberLimit) {
            uni.showToast({
              title: `最少选择${this.hotelOrderInfo.minRoomNumberLimit}间`,
              icon: "none",
            });
            return;
          }
        } else {
            if (this.roomNight <= 1) {
              uni.showToast({
                title: "最少选择1间",
                icon: "none",
              });
              return;
            }
        }
        this.roomNight--;
        let x = this.$BigNumber(this.price).times(this.roomNight).toString();
        this.$emit("setParentLevelData", {
          totalPrice: x,
        });

        var num = this.roomNight;
        let popArr = JSON.parse(JSON.stringify(this.$store.$state.formData));
        num--;
        if (popArr.length > 2) {
          popArr.pop();
        }
        // this.formData = popArr;
        this.$store.commit("SET_FORMDATA", popArr);
        this.$refs.carRef.getReservation();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.info-box {
  width: 710rpx;
  background: #ffffff;
  border-radius: 30rpx 30rpx 30rpx 30rpx;
  margin: 0 auto;
  .margin-box {
    width: 650rpx;
    margin: 8rpx auto;
    .title {
      width: 100%;
      height: 105rpx;
      border-bottom: 1rpx solid #E4E4F4;
      line-height: 105rpx;
      font-size: 32rpx;
      color: $sl-color-black;
      margin-bottom: 30rpx;
      font-weight: 600;
    }
    .info-flex {
      display: flex;
      // align-items: center;
      padding-bottom: 30rpx;
      font-weight: 400;
      .flex-label {
        color: $sl-color-grey;
        font-size: 28rpx;
        width: 157rpx;
      }
      .flex-content {
        flex: 1;
        color: $sl-color-dark-grey;
        font-size: 28rpx;
      }
      .flex-content.active {
        display: flex;
        flex-direction: column;
        .view {
          padding-bottom: 10rpx;
          color: #4d566a;
          font-size: 28rpx;
        }
      }
      .flex-right-box {
        display: flex;
        align-items: center;
        .change-btn {
          width: 44rpx;
          height: 44rpx;
        }
        .roomNight {
          height: 44rpx;
          line-height: 44rpx;
          padding: 0 30rpx;
          color: $sl-color-grey;
          font-size: 36rpx;
        }
      }
      .checkInTime {
        height: 42rpx;
        border-radius: 21rpx;
        border: 1rpx solid $sl-color-blue;
        padding: 0 14rpx;
        color: $sl-color-blue;
        font-size: 20rpx;
        text-align: center;
        line-height: 42rpx;
      }
    }
    .info-flex.active {
      justify-content: space-between;
    }
  }
}
</style>